package com.fuchenyang.consumer.Service.Impl;

import com.fuchenyang.common.util.JsonResult;
import com.fuchenyang.consumer.Service.ConsumerService;
import jakarta.annotation.Resource;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
@Service
public class ConsumerServiceImpl implements ConsumerService {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;


    // 集群调用
    private int index = 0;

    /**
     * 普通调用
     * @return
     */
    @Override
    public JsonResult a() {
        // 发现
        List<ServiceInstance> instances = discoveryClient.getInstances("example-provider");
        ServiceInstance instance = instances.get(index);
        if (index == 2) {
            index = 0;
        } else {
            index++;
        }
        // 调用
        String url = instance.getUri().toString() + "/provider/a"; // http://localhost:8010
        return restTemplate.getForObject(url, JsonResult.class);
    }

    @Override
    public JsonResult b(String name) {
        // 发现
        List<ServiceInstance> instances = discoveryClient.getInstances("example-provider");
        ServiceInstance instance = instances.get(index);
        if (index == 2) {
            index = 0;
        } else {
            index++;
        }
        // 调用
        String url = instance.getUri().toString() + "/provider/b/" + name; // http://localhost:8010
        return restTemplate.getForObject(url, JsonResult.class);
    }


}
